package br.siseventos.managed;

import br.siseventos.util.FacesUtil;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;

@ManagedBean(name = "usuarioBean")
@SessionScoped
public class UsuarioBean extends BaseBean {
    // Campos

    Logger log = Logger.getLogger(UsuarioBean.class);
    @ManagedProperty(value = "#{authenticationManager}")
    private AuthenticationManager authenticationManager;
    private String login;
    private String senha;

    // Construtor
    public UsuarioBean() {
    }

    // Serviço
    public String logar() {

        try {
            String url = FacesUtil.getExternalContext().getRequestContextPath() + "j_spring_security_check";
            RequestDispatcher dispatcher = FacesUtil.getServletRequest().getRequestDispatcher(url);
            dispatcher.forward(FacesUtil.getServletRequest(), FacesUtil.getServletResponse());
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception ex) {
            //FacesUtil.exibirMensagemErro(ex.getMessage());
            return null;
        }
        return null;
    }

    public boolean isLogged() {
        boolean logado = false;
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal.compareTo("anonymousUser") != 0) {
            logado = true;
        }
        return logado;
    }

    public String showLoginBox() {
        String result = "inline-block";
        if (isLogged()) {
            result = "none";
        }
        return result;
    }

    public String showErrorRow(boolean show) {
        String result = "none";
        if (show) {
            result = "block";
        }
        return result;
    }
    // Getters e Setters

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public boolean isAdmin() {
        return true;
    }

    public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
}
